import java.util.HashMap;
import java.util.Map;

public class CustomerStorage {
    private final Map<String, Customer> storage;

    public CustomerStorage() {
        storage = new HashMap<>();
    }

    public void addCustomer(String data)
            throws CommandFormatException, PhoneNumberFormatException, EmailFormatException {
        final int INDEX_NAME = 0;
        final int INDEX_SURNAME = 1;
        final int INDEX_EMAIL = 2;
        final int INDEX_PHONE = 3;

        String[] components = data.split("\\s+");
        if (components.length != 4) {
            throw new CommandFormatException();
        }

        String name = components[INDEX_NAME] + " " + components[INDEX_SURNAME];
        storage.put(name,
                new Customer(name,
                        formatPhoneNumber(components[INDEX_PHONE]),
                        formatEmail(components[INDEX_EMAIL])
                )
        );
    }

    public void listCustomers() {
        storage.values().forEach(System.out::println);
    }

    public void removeCustomer(String name) {
        storage.remove(name);
    }

    public Customer getCustomer(String name) {
        return storage.get(name);
    }

    public int getCount() {
        return storage.size();
    }

    private String formatPhoneNumber(String phone) throws PhoneNumberFormatException {
        if (!phone.matches("^\\+\\d{10,}$")) {
            throw new PhoneNumberFormatException();
        }

        return phone;
    }

    private String formatEmail(String email) throws EmailFormatException {
        if (!email.matches("^\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$")) {
            throw new EmailFormatException();
        }

        return email;
    }
}